import { UserModule } from '@/store/modules/user';
import { DirectiveBinding, DirectiveOptions } from 'vue/types/options';

const permission: DirectiveOptions = {
  /**
   * @direction permisstion
   * @module v-permission=['admin','editor']
   * 检测store权限,处理是否显示元素
   */
  inserted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    const roles = UserModule.resourceKeys;

    if (value && value instanceof Array && value.length > 0) {
      const permissionRoles = value;

      const hasPermission = roles.some((role: string) => {
        return permissionRoles.includes(role);
      });

      if (!hasPermission) {
        // tslint:disable-next-line:no-unused-expression
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error(`无效规则! 请按照 v-permission=['roles'...]`);
    }
  }
};

export default permission;
